package back.controller;

import back.pojo.R;
import back.pojo.User;
import back.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Random;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @GetMapping({"/","/login"})
    public String getLogin(){
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public R postLogin(User user, HttpSession session){
        R r = new R();
        HashMap<String, Object> data = new HashMap<String, Object>();
        for (User getUser : userService.getUsers(new User())) {
            if (getUser.getUserName().equals(user.getUserName()) && getUser.getPassword().equals(user.getPassword())){
                session.setAttribute("user",user.getUserName());
                r.setCode(200);
                r.setMsg("登陆成功");
                data.put("user", user);
                r.setData(data);
                break;
            }else {
                r.setCode(401);
                r.setMsg("用户不存在");
                r.setData(data);
                break;
            }
        }
        return r;
    }


    @GetMapping("/logout")
    public String logout(HttpSession session) throws Exception {
        // 移除session
        session.removeAttribute("user");
        return "login";
    }

    @GetMapping("/test")
//    @ResponseBody
    public String test(){
//        return userService.getUsers();
        return "index";
    }
}
